package phoneinterface;

import java.net.*;
import java.util.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: </p>
 * @author Tan, Khew, Fan
 * @version 1.0
 */

public class IP {

  public static final int NUM_FIELD = 4;

  private InetAddress address;

  private IP() {}

  public static IP getIP(InetAddress address) {
    IP result = new IP();
    result.address = address;
    return result;
  }

  public static IP getIP(String ip) {
    byte[] addr = new byte[NUM_FIELD];
    try {
      StringTokenizer tokenizer = new StringTokenizer(ip, ".");
      int cnt = 0;
      while ( tokenizer.hasMoreTokens() ) {
        if ( cnt == NUM_FIELD ) {
          return null;
        }
        Integer in = new Integer(tokenizer.nextToken());
        addr[cnt++] = (byte)in.intValue();
      }
      if ( cnt != NUM_FIELD ) {
        return null;
      }
      IP result = new IP();
      result.address = InetAddress.getByAddress(addr);
      return result;
    }
    catch ( Exception e ) {
      return null;
    }
  }

  public String getString() {
    String result = "";
    byte[] addr = address.getAddress();
    for ( int i=0; i<NUM_FIELD; i++ ) {
      result += "" + (((int)addr[i]) & 0xff);
      if ( i<NUM_FIELD-1 ) {
        result += ".";
      }
    }
    return result;
  }

  public InetAddress getAddress() {
    return address;
  }

}